package com.example.hello.service.impl;

import com.example.hello.config.ObjectStorageConfig;
import com.example.hello.exception.BusinessException;
import com.example.hello.service.FileService;
import io.minio.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {

    private final ObjectStorageConfig config;
    private final MinioClient minioClient;

    @Override
    public String uploadFile(MultipartFile file) {
        try {
            // 校验文件
            if (file.isEmpty()) {
                throw new BusinessException("文件不能为空");
            }
            
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                throw new BusinessException("文件名不能为空");
            }

            // 校验文件大小（2M）
            if (file.getSize() > 2 * 1024 * 1024) {
                throw new BusinessException("文件大小不能超过2M");
            }

            // 校验文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                throw new BusinessException("只支持图片文件上传");
            }

            // 检查桶是否存在，不存在则创建
            String bucketName = config.getBucketName();
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder()
                    .bucket(bucketName)
                    .build());
            if (!bucketExists) {
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(bucketName)
                        .build());
                log.info("Bucket {} created successfully", bucketName);
            }

            // 生成文件路径
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + fileExtension;
            String datePath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            String objectName = datePath + "/" + fileName;

            // 上传文件
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(contentType)
                    .build());

            log.info("File uploaded successfully: {}/{}", bucketName, objectName);

            // 返回文件访问路径
            return String.format("https://%s/%s/%s", 
                config.getEndpoint(), 
                bucketName, 
                objectName);

        } catch (Exception e) {
            log.error("File upload failed", e);
            throw new BusinessException("文件上传失败：" + e.getMessage());
        }
    }
} 